package com.example.newbiechen.ireader.model.remote;

import com.example.newbiechen.ireader.model.bean.BookChapterBean;
import com.example.newbiechen.ireader.model.bean.ChapterInfoBean;
import com.example.newbiechen.ireader.model.bean.ChapterInfoPackage;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Single;
import retrofit2.Retrofit;


public class RemoteRepository {

    private static RemoteRepository sInstance;
    private BookApi mBookApi;

    private RemoteRepository() {
        Retrofit mRetrofit = RemoteHelper.getInstance().getRetrofit();
        mBookApi = mRetrofit.create(BookApi.class);
    }

    public static RemoteRepository getInstance() {
        if (sInstance == null) {
            synchronized (RemoteHelper.class) {
                if (sInstance == null) {
                    sInstance = new RemoteRepository();
                }
            }
        }
        return sInstance;
    }


    /**
     * 根据 id 获取 所有 章节列表
     */
    public Single<List<BookChapterBean>> getBookChapters(String bookId) {
        return mBookApi.getBookChapterPackage(bookId, "chapter")
                .map(
                        bean -> {
                            if (bean.getMixToc() == null) {
                                return new ArrayList<BookChapterBean>(1);
                            } else {
                                return bean.getMixToc().getChapters();
                            }
                        });
    }

    /**
     * 注意这里用的是同步请求
     */
    public Single<ChapterInfoBean> getChapterInfo(String url) {
        return mBookApi.getChapterInfoPackage(url).map(ChapterInfoPackage::getChapter);
    }


}
